﻿package org.dm.3d.Actions.object 
{
	import org.dm.3d.Actions.Action;
	import org.dm.3d.geom.Num3D;
	import org.dm.3d.geom.MathExtend;
	
	/**
	 * ...
	 * @author Scott
	 */
	public class Plane extends Action
	{
		private var _width:Number;
		private var _height:Number;
		private var _cur:uint = 0;
		private var _pre:Boolean = true;
		private var _speed:Number = 201;
		private var goalNum:uint;
		
		public function Plane() 
		{
			this.isUsed = true;
			_width = 10.5373;
			_height = 10.5405;
			goalNum = 2412;
		}
		public override function update(items:Array, num:uint):void 
		{
			_cur++;
			for (var m:uint = 0; m < num; m++)
			{
				items[m].visable = true;
			}
			if (_cur < 10)
			{
				if (_pre) preMove(items, num, 1000);
			}
			if (_cur < 21) return;
			if (_cur < 33) 
			{
				addSpeed(items,(_cur-21)*_speed);
			}
			if (_cur >= 31)
			{
				
				var kmax:uint = (_cur - 31) * _speed ;
				var tspeed:Num3D;
				var addk:uint = _speed;
				if (kmax > goalNum)
				{
					kmax = goalNum;
				}
				if (_cur >42) addk = 0;
				if(addk>0)
					for (var k:uint = 0; k < addk; k++)
					{
						items[(_cur-31)*_speed+k].opos = items[(_cur-31)*_speed+k].pos.clone();
					}
				for (k = 0; k < kmax; k++)
				{
					tspeed = items[k].opos.subtract(items[k].pos);
					items[k].damping = .6;
					tspeed.scaleBy(.8);
					items[k].acceleration = tspeed;
				}
			}
			for (var n:uint = 2412; n < num; n++)
				items[n].visable = false;
		}
		public function addSpeed(items:Array,pcur:uint):void 
		{
			var left:uint = pcur + _speed;
			var w:Number;
			var h:Number;
			left = left > goalNum?goalNum:left;
			for (var i:uint = pcur; i < left;i++ )
			{
				w = i % 67;
				w = w *_width-353;
				h = _height * int(i / 67) - 235;//195;
				
				var damping:Number = items[i].damping;
				damping = (1 - damping) / (1 - Math.pow(damping, 10));
				var tvc:Num3D = new Num3D(w, h, 0);
				tvc.decrementBy(items[i].pos);
				tvc.scaleBy(damping);
				items[i].speed = tvc;
			}
		}
		public function preMove(items:Array,num:uint,distance:Number):void 
		{
			var tvc:Num3D;
			var damping:Number;
			damping = .95;
			damping = (1 - damping) / (1 - Math.pow(damping, 20));
			for (var i:uint = 0; i < num; i++)
			{
				items[i].visable = true;
				tvc = MathExtend.pInRound(i, 50, distance);
				tvc.decrementBy(items[i].pos);
				tvc.scaleBy(damping);
				items[i].speed = tvc;
			}
			this._pre = false;
		}
	}
	
}